
import hashlib
import requests
import json
from Config import *
from datetime import datetime, timedelta
import enum

class Status(enum.Enum):
    TODO = '预告中'
    DOING = '进行中'
    DONE = '已成交'
    BREAK = '已暂缓'
    STOP = '已中止'
    REVOCATION = '已撤回'
    FAILURE = '已流拍'


#计算字符串的MD5
def Str2MD5(Str) -> str:
    MD5 = hashlib.md5(Str.strip().encode("utf-8")).hexdigest();
    return MD5;
    
#使用Get方式请求一个URL
def HtmlGet(URL, params=None):
    if params is None:
        params = {"lanSign": Config["Spider"]["lanSign"]}
    else:
        params["lanSign"] = Config["Spider"]["lanSign"]
        
    #访问网页
    result = requests.get(URL,  params=params);
    # print("request url="+URL+"，response=", result.text);
    return result;
    #end

def HtmlPost(URL, data= None):
    if data is None:
        data = {"lanSign": Config["Spider"]["lanSign"]}
    else:
        data["lanSign"] = Config["Spider"]["lanSign"]
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    # dataStr = json.dumps(data, ensure_ascii=False)
    # dataStr8 = dataStr.encode('utf-8')
    # jsonData = json.loads(dataStr8);
    result = requests.post(URL, json=data, headers=headers)
    return result;

def PageListSave(data):
    HtmlPost(Config["Spider"]["apiRoot"]+"/spider/client/list", data);

def PageDetailSave(data):
    HtmlPost(Config["Spider"]["apiRoot"]+"/spider/client/detail", data);

def PageDetailFail(id):
    HtmlGet(Config["Spider"]["apiRoot"]+"/spider/client/detailfail/"+id);

#向管理员发送告警通知
def WarningPrompt(Type=None):
    print("Warning Prompt!!! Type=", str(Type));
    if Type==None:
        params = None;
    else:
        params = {'type':str(Type)};

    #执行页面Get
    HtmlGet(Config["Spider"]["apiRoot"]+"/spider/warn/notify", params);
    # 有告警则状态修改为人机验证
    StatusModify(Status=5)
    #end

# 修改爬虫服务器状态
def StatusModify(Status=None):
    if Status==None:
        return
    
    params = {'status':Status};
    # print("Spider Status Modify !!! Status=", Status);
    #执行页面Get
    HtmlGet(Config["Spider"]["apiRoot"]+"/spider/server/status", params);
    #end

# 爬取次数+1
def RunCountAdd():
    #执行页面Get
    HtmlGet(Config["Spider"]["apiRoot"]+"/spider/server/countadd");

# 查询爬虫参数
def SpiderParams():
    #执行页面Get
    result = HtmlGet(Config["Spider"]["apiRoot"]+"/spider/server/params");
    return result

def GetSpiderParams():
    ParaMap  = {};
    result = SpiderParams()
    RJson = json.loads(result.text);
    ParaMap['threadNum'] = Config["Spider"]['threadNum'];
    ParaMap['grabCity'] = None;
    ParaMap['grabDistrict'] = None;
    ParaMap['houseType'] = None;
    ParaMap['grabPage'] = None;
    ParaMap['serverIp'] = "127.0.0.1";
    ParaMap['realIp'] = '0.0.0.0';

    proxyForm = ',Jd,Gpw,Zppt,Sszcw,Icbc,Cbex'

    if 'data' in RJson:
        if 'realIp' in RJson['data']:
            ParaMap['realIp'] = RJson['data']['realIp']
        
        for item in proxyForm.split(","):
            ParaMap['proxyUrl'+item] = None;
            if 'proxyipUrl'+item in RJson['data']:
                proxyUrl = RJson['data']['proxyipUrl'+item]
                if proxyUrl != None and len(proxyUrl) > 10:
                    ParaMap['proxyUrl'+item] = proxyUrl
        if 'threadNum' in RJson['data']:
            ParaMap['threadNum'] = RJson['data']['threadNum']
        if 'grabCity' in RJson['data'] and len(RJson['data']['grabCity']) > 0:
            ParaMap['grabCity'] = RJson['data']['grabCity']
        if 'grabDistrict' in RJson['data'] and len(RJson['data']['grabDistrict']) > 0:
            ParaMap['grabDistrict'] = RJson['data']['grabDistrict']
        if 'houseType' in RJson['data'] and len(RJson['data']['houseType']) > 0:
            ParaMap['houseType'] = RJson['data']['houseType']
        if 'grabPage' in RJson['data'] and len(RJson['data']['grabPage']) > 0:
            ParaMap['grabPage'] = int(RJson['data']['grabPage'])
        if 'serverIp' in RJson['data'] and len(RJson['data']['serverIp']) > 0:
            ParaMap['serverIp'] = RJson['data']['serverIp']
    print("param=", ParaMap)
    return ParaMap

def StatusDictAli(statusFlag):
    sd = {
        "pai-status-todo": Status.TODO.value,
        "pai-status-doing": Status.DOING.value,
        "pai-status-done": Status.DONE.value,
        "pai-status-failure": Status.FAILURE.value, # 列表中在结束状态里
        "pai-status-break": Status.BREAK.value,
        "pai-status-revocation": Status.REVOCATION.value

    }
    return sd[statusFlag];

def CheckChinese(string):
    for char in string:
        if '\u4e00' <= char <= '\u9fa5':
            return True
    return False

def has_numbers(string):
    return any(char.isdigit() for char in string)

def AmountHandle(string):
    if '-' in string or '待定' in string:
        return 0
    string = string.strip().replace(',', '');
    if '亿' in string:
        return int(float(string.replace('亿元', '').replace('亿', '')) * 100000000);
    if '万' in string:
        return int(float(string.replace('万元', '').replace('万', '')) * 10000);
    elif '元' in string:
        return int(float(string.replace('元', '')));
    else:
        return int(float(string));

def DateHandle(date_str):
    # 将日期字符串转换为datetime对象
    date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    # 将datetime对象转换为指定格式的字符串
    formatted_date_str = date_obj.strftime("%Y-%m-%d %H:%M:%S")
    return formatted_date_str

def DateHandle1(date_str):
    dt = datetime.strptime(date_str, "%Y年%m月%d日 %H:%M")
    return dt.strftime("%Y-%m-%d %H:%M:%S")

def change_date(date_str, days):
    dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    new_dt = dt + timedelta(days=days)
    return new_dt.strftime("%Y-%m-%d %H:%M:%S")

if __name__ == "__main__":

    # WarningPrompt(Type=92)
    # StatusModify(Status=2)
    # (proxyIp, threadNum) = GetSpiderParams()
    # print(proxyIp, threadNum)
    # print (DateHandle("2023-7-20 10:1:00"))
    print(AmountHandle('1.314017亿'))
    




    

